open Target
(* n is the number of tasks    *)
(* m is the number of machines *)
let n = int_of_string Sys.argv.(1)
let m = int_of_string Sys.argv.(2)

let width = 600
let height = 600


let coord = 
Array.init (n+2*m) 
  (fun k -> 
     if k < n+m
     then
       ((float width) /. 2. -. Random.float (float width), 
	(float height)/. 2. -. Random.float (float height))
     else
       (0., 0.)
  )


let wind_dir = Random.float 360.
let wind_speed = 5. *. (float (Random.int 4)) 

let video = Array.init m (fun _ -> 1)
let ball  = Array.init m (fun _ -> 1)

let distance = fun (x1, y1) (x2, y2) -> 
  let x1 = 4. *. x1 and
      x2 = 4. *. x2 and
      y1 = 4. *. y1 and
      y2 = 4. *. y2 in
  sqrt ((x1-.x2)** 2. +. (y1-. y2)**2.)

let task_time = 60
let ac_speed = 20.

let time = 
  Array.init m 
    (fun _ ->
       Array.init (n+2*m)
	 (fun k ->
	    Array.init (n+2*m) 
	      (fun p ->
		 if (k>=n+m) && (p= k-m)
		 then 0
		 else
		   let alpha = 
		     let (x1, y1) = coord.(k) and
			 (x2, y2) = coord.(p) in
		     (atan2 (y2 -. y1) (x2 -. x1)) -. wind_dir
		   in
		   let speed = wind_speed *. cos alpha 
		     +. sqrt (wind_speed**2. *. (sin alpha)**2. 
			      +. ac_speed**2.) in
		 int_of_float 
		   ((distance coord.(k) coord.(p)) /. speed) + task_time
	      )
	 )
    )
	      

(*let min_time = 
  let x = ref max_int in
  for i=0 to Array.length time-1 do
    for j=0 to Array.length time.(i) -1 do
      for k=0 to Array.length time.(i).(j) -1 do
	if j < n+m then
	  x := min !x time.(i).(j).(k);
      done
    done
  done;
  Printf.printf "smallest time:%d \n" !x*)

let tto = Array.init m (fun _ -> 50)

let ttype = Array.init n 
	(fun k ->
	   if k < m then Dr
	   else Id
	)

let deadline = 1800




let trace = let call = ref false in fun plans ->

  let wait = fun () ->
  let t0 = Sys.time () in
    while Sys.time () -. t0 < 0.1 do
      ignore true;
    done in

  if not !call then begin
    call := true;
    Graphics.open_graph (" "^(string_of_int width)^"x"^(string_of_int height));
  end 
  else begin
    wait ();
    Graphics.clear_graph ();
  end;
  let trans = fun (x,y) ->
    (int_of_float (x+. (float (width/2))), int_of_float (y+. (float (height/2)))) 
  in
  let draw_target = fun i (x,y) ->
    if i < Array.length ttype then begin
      let (x,y) = trans (x,y) in
      Graphics.set_color Graphics.black;
      if ttype.(i) = Dr 
      then Graphics.draw_rect (x-3) (y-3) 6 6
      else Graphics.draw_circle x y 4 
    end
  in
    (* draw targets *)
  Array.iteri (fun i (x,y) -> draw_target i (x,y) ) coord;
  let colors = [| 
    Graphics.black;
    Graphics.red;
    Graphics.green;
    Graphics.blue;
    Graphics.yellow;
    Graphics.cyan;
    Graphics.magenta |] in
  
    Array.iteri 
      (fun i a -> 
	 Graphics.set_color colors.(i mod 8);
	 Graphics.draw_poly_line
	   (Array.map (fun i ->
			 trans coord.(i)) a)
      ) plans

(*let trace = fun plans -> ()*)

